#!/bin/bash
# 安装maas 3.4
source comm.cfg

color_text() {
    local color=$1
    local text=$2
    echo -e "\e[${color}m${text}\e[0m"
}

error() {
    color_text "31" "$1"
}

info() {
    color_text "32" "$1"
}

installmaas01() {
    # 创建 MaaS 数据库用户
    sudo -u postgres psql -c "CREATE USER \"maascli\" WITH PASSWORD 'a3f876fb3286e8bf304c01064e080fae'"
    sudo -u postgres createdb -O "maascli" "maasclidb"
    # 可以修改成其他版本
    sudo snap install --channel=${MAASVERSION} maas 
    # 初始化 MaaS 数据库，使用pg的VIP地址
    sudo maas init region+rack --database-uri "postgres://maascli:a3f876fb3286e8bf304c01064e080fae@${PG_HOST}/maasclidb" --maas-url http://${MAAS01}:5240/MAAS
    sudo maas status
    info "请在${MAAS01}节点执行sudo maas createadmin创建admin用户，然后在浏览器登录"
}

installmaas02() {
    maasready ${MAAS01}
    sudo snap install --channel=${MAASVERSION} maas
    sudo maas init region+rack --database-uri "postgres://maascli:a3f876fb3286e8bf304c01064e080fae@${PG_HOST}/maasclidb" --maas-url http://${MAAS02}:5240/MAAS
    sudo maas status
    info "请在${MAAS02}节点执行sudo maas createadmin创建admin用户，然后在浏览器登录"
}

# 等等另一个节点初始化完成
maasready() {
    for i in $(seq 1 60)
    do
        nc -zv $1 5240 &> /dev/null
        if [ $? -ne 0 ];then
            error "Waiting Ready......"
            sleep 10
        else
            info "$1 MAAS Is Ready"
            return 0
        fi
    done
    error "Waiting MAAS Timeout"
    exit 1
}

install() {
    ip a | grep ${MAAS01} &>/dev/null
    if [ $? -eq 0 ];then
        installmaas01
    else
        installmaas02
    fi
}

install